package qs.openxt.libs.qrcode;

import java.util.Hashtable;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;

import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;
import com.mining.app.zxing.decoding.RGBLuminanceSource;
import qs.openxt.libs.util.StringUtil;

public class QrcodeTask extends AsyncTask<String, Integer, String> {
	private QrcodeTasking callBack = null;

	public QrcodeTask(QrcodeTasking callBack) {
		this.callBack = callBack;
	}

	public boolean cancelTask() {
		if (cancel(true)) {
			this.callBack = null;
			return true;
		}
		return false;
	}

	protected String doInBackground(String... params) {
		return doScanningImage(params[0]);
	}

	protected void onPostExecute(String result) {
		super.onPostExecute(result);
		if(result != null && this.callBack != null)
			this.callBack.onSuccess(result);
		else if(this.callBack != null)
			this.callBack.onError();
	}
	
	
	private String doScanningImage(String path){
		try {
			if (StringUtil.isNull(path)) {
				return null;
			}
			Hashtable<DecodeHintType, String> hints = new Hashtable<DecodeHintType, String>();
			hints.put(DecodeHintType.CHARACTER_SET, "utf-8"); // 设置二维码内容的编码

			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inJustDecodeBounds = true; // 先获取原大小
			Bitmap scanBitmap = BitmapFactory.decodeFile(path, options);
			options.inJustDecodeBounds = false; // 获取新的大小
			int sampleSize = (int) (options.outHeight / (float) 200);
			if (sampleSize <= 0)
				sampleSize = 1;
			options.inSampleSize = sampleSize;
			scanBitmap = BitmapFactory.decodeFile(path, options);
			RGBLuminanceSource source = new RGBLuminanceSource(scanBitmap);
			BinaryBitmap bitmap1 = new BinaryBitmap(new HybridBinarizer(source));
			QRCodeReader reader = new QRCodeReader();
			Result result = reader.decode(bitmap1, hints);
			return result.getText();
		} catch (Exception e) {
		}
		return null;
	}
}